package com.skynet.supervision.config.jackson;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.skynet.supervision.utils.Strings;
import lombok.val;

import java.io.IOException;

public final class JacksonStringDeserializer extends JsonDeserializer<String> {
    public static final JacksonStringDeserializer INSTANCE = new JacksonStringDeserializer();
    @Override
    public String deserialize(JsonParser p, DeserializationContext ctx) throws IOException, JsonProcessingException {
        val pt = p.currentToken();
        if (pt == JsonToken.VALUE_NULL) {
            return null;
        }
        if (pt==JsonToken.VALUE_STRING) {
            return p.getValueAsString().trim();
        }
        throw new JsonParseException(p, Strings.sprintf(" {} 不是合法的字符串参数", p.getCurrentName()));
    }
}
